<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 商城小程序公共API服务
 */
namespace app\allwin\controller\api\v4;
use app\allwin\controller\api\Base;
use app\allwin\model\AllwinShop;
use app\allwin\model\AllwinShopCate;
use app\allwin\model\AllwinShopOrder;
use app\common\model\SystemUser;
use util\Util;

class Shop extends Base{

    
   /**
     * 首页显示
     */
    public function index(){
        $param['signkey'] = $this->request->param('signkey');
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $rel = AllwinShop::where(['member_miniapp_id' => $this->miniapp_id,'types' => 1,'is_sale' => 1,'is_del' => 0])->field('id,category_id,name,title,img,sell_price,end_time')->limit(8)->select();
        $data = [];
        foreach ($rel as $key => $value) {
            $data[$key] = $value;
            $data[$key]['coupon_price'] = money(empty($value->coupon) ? 0 : AllwinShop::calculatePrice($value->sell_price,$value->coupon));
            $data[$key]['img']          = $value->img.'?x-oss-process=style/640';
            $data[$key]['tags']         = time()-$value->update_time <= 86400 ? '上新':'';
        }
        return enjson(200,'成功',$data);
    }

   /**
     * 首页推荐专题
     */
    public function indexSpecial(){
        $param['signkey'] = $this->request->param('signkey');
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $cate = AllwinShopCate::where(['member_miniapp_id' => $this->miniapp_id,'types' => 1])->field('id,title,content,picture')->select();
        if(empty($cate)){
            return enjson(200);
        }
        $cate_id = array_column($cate->toArray(),'id');
        $rel = AllwinShop::whereIN('category_id',$cate_id)->where(['types' => 2,'is_sale' => 1,'is_del' => 0])->field('id,category_id,name,title,img,points,warehouse_num,sell_price,market_price,vip_price,coupon_id,end_time,update_time')->limit(8)->select();
        $shop = [];
        foreach ($rel as $key => $value) {
            $shop[$key] = $value;
            $shop[$key]['coupon_price'] =  money(empty($value->coupon) ? 0 : AllwinShop::calculatePrice($value->sell_price,$value->coupon));
            $shop[$key]['img']          = $value->img.'?x-oss-process=style/640';
            $shop[$key]['tags']         = time()-$value->update_time <= 86400 ? '上新':'';
            $end_time                   = $value['warehouse_num'] ? (($value->end_time + 60 * 10) - time()) * 1000 : 0;
            $shop[$key]['end_time']     = $end_time ?: 0;
        }
        $goods = dataGroup($shop,'category_id');
        $data = [];
        foreach ($cate as $key => $value) {
            $data[$key] = $value;
            $data[$key]['goods'] = $goods[$value['id']] ?? [];
        }
        return enjson(200,'成功',$data);
    }
   
   /**
     * 专栏专题页面
     */
    public function special(){
        $param['id']   = $this->request->param('id/d');
        $param['page'] = $this->request->param('page/d',0);
        $param['sign'] = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $cate = [];
        if($param['page'] == 1){
            $cate = AllwinShopCate::where(['member_miniapp_id' => $this->miniapp_id,'id' => $param['id']])->field('id,title,content,picture')->find();
            if(empty($cate)){
                return enjson(403);
            }
        }
        $rel = AllwinShop::where(['is_sale' => 1,'is_del' => 0,'category_id' => $param['id']])->field('id,share_price,detective_price,store_id,category_id,name,title,img,warehouse_num,points,sell_price,market_price,vip_price,coupon_id,end_time,update_time')->paginate(10);
        if($rel->isEmpty()){
            return enjson(204);
        }
        $shop = [];
        foreach ($rel as $key => $value) {
            $shop[$key] = $value;
            $shop[$key]['coupon_price'] =  money(empty($value->coupon) ? 0 : AllwinShop::calculatePrice($value->sell_price,$value->coupon));
            $shop[$key]['img']          = $value->img.'?x-oss-process=style/640';
            $shop[$key]['tags']         = time()-$value->update_time <= 86400 ? '上新':'';
            $end_time                   = $value['warehouse_num'] ? (($value->end_time + 60 * 10) - time()) * 1000 : 0;
            $shop[$key]['end_time']     = $end_time ?: 0;
        }
        return enjson(200,'成功',['shop' => $shop,'special' => $cate]);
    }

    /**
     * 根据条件查询数据
     */
    public function goods(){
        $param['page']    = $this->request->param('page/d',1);
        $param['types']   = $this->request->param('types/d',0);
        $param['store_id']= $this->request->param('store_id/d',0);
        $param['keyword'] = $this->request->param('keyword','');
        $param['signkey'] = $this->request->param('signkey');
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $where = [];
        $where['is_del']  = 0;
        $where['is_sale'] = 1;
        $where['member_miniapp_id'] = $this->miniapp_id;
        if($param['types']){
            $where['types'] = $param['types'];
        }
        if($param['store_id']){
            $where['store_id'] = $param['store_id'];
        }
        $special = AllwinShop::where($where)->withSearch(['name'],['name' => $param['keyword']])->field('id,share_price,detective_price,store_id,category_id,name,title,img,warehouse_num,points,sell_price,market_price,vip_price,coupon_id,end_time,update_time')->paginate(10);
        if($special->isEmpty()){
            return enjson(204);
        }
        $data = [];
        foreach ($special as $key => $value) {
            $data[$key] = $value;
            $data[$key]['store_name']   = $value->store->name;
            $data[$key]['distance']     = getDistance($this->qqgps['lng'],$this->qqgps['lat'],$value->store->longitude,$value->store->latitude);
            $data[$key]['tags']         = time()-$value->update_time <= 86400 ? '上新':'';
            $data[$key]['coupon_price'] = money(empty($value->coupon) ? 0 : AllwinShop::calculatePrice($value->sell_price,$value->coupon));
            $data[$key]['img']          = $value->img.'?x-oss-process=style/640';
            //计算价格
            $price                         = $value->sell_price-$value->vip_price-$data[$key]['coupon_price']-$value->points/100;
            $data[$key]['share_price']     = money($price*$value->share_price/100);
            $data[$key]['detective_price'] = money($price*$value->detective_price/100);
            $end_time                      = $value['warehouse_num'] ? (($value->end_time + 60 * 10) - time()) * 1000 : 0;
            $data[$key]['end_time']        = $end_time ?: 0;
        }

        return enjson(200,'成功',$data);
    }

    /**
     * 读取单个商品信息
     * @param integer $id 商品ID
     * @return void
     */
    public function item(){
        $param['id']      = $this->request->param('id/d',0);
        $param['signkey'] = $this->request->param('signkey');
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        //查找商品SPU
        $item = AllwinShop::where(['is_sale'=>1,'id' => $param['id'],'member_miniapp_id' => $this->miniapp_id])
        ->field('id,store_id,category_id,warehouse_num,warehouse_sellnum,like,group_title,group_img,group_note,coupon_id,name,title,img,imgs,points,sell_price,market_price,end_time,content,notice,keyword,vip_price')
        ->find();
        if(empty($item)){
            return json(['code'=>403,'msg'=>'没有内容']);
        }
        $item->like += 1;
        $item->save();
        $store = [];
        if($item->store_id > 0){
            $store['img'] = $item->store['img']."?x-oss-process=style/w100";
            $imgs = empty($item->store['imgs']) ? [] :json_decode($item->store['imgs']);
            $imga = [];
            foreach ($imgs as $key => $img) {
                $imga[$key] = $img."?x-oss-process=style/w300";
            }
            $store['imgs'] = $imga;
            $store['create_time'] = util::ftime($item->store->create_time);
            $store['tags']    = explode(',',$item->store->tags); 
            $store['name']    = $item->store->name; 
            $store['address'] = $item->store->address; 
            $store['tips']    = $item->store->tips; 
            $store['distance'] = getDistance($this->qqgps['lng'],$this->qqgps['lat'],$item->store->longitude,$item->store->latitude);
            $store['chains'] = [];
            if(!empty($item->store->chains)){
                $chains = $item->store->chains;
                $chain = [];
                foreach ($chains as $key => $value) {
                    $chain[$key]['title']    = $value['title'];
                    $chain[$key]['address']  = $value['address'];
                    $chain[$key]['telphone'] = $value['telphone'];
                    $chain[$key]['distance'] = getDistance($this->qqgps['lng'],$this->qqgps['lat'],$value->longitude,$value->latitude);
                }
                $store['chains'] = $chain;
            }
        }
        $item['content']      = str_replace('<img', '<img class="img" style="max-width:100%;height:auto"',dehtml($item['content']));
        $item['notice']       = str_replace('<img', '<img class="img" style="max-width:100%;height:auto"',dehtml($item['notice']));
        $item['market_price'] = money($item['market_price']);
        $item['sell_price']   = money($item['sell_price']);
        $item['img']          = $item['img'].'?x-oss-process=style/500';
        $item['imgs']         = json_decode($item['imgs'],true);
        $item['coupon_id']    = $item->coupon_id;
        $item['coupon_price'] = money(empty($item->coupon) ? 0 : AllwinShop::calculatePrice($item->sell_price,$item->coupon));
        $item['points_price'] = money($item->points/100);
        $item['tags']         = time()-$item->update_time <= 86400 ? '上新':'';
        $order_num            = AllwinShopOrder::where(['shop_id' => $item->id,'paid_at'=>1])->count();
        $item['order_num']    = $item['warehouse_sellnum']+$order_num;
        $end_time             = $item['warehouse_num'] ? (($item->end_time + 60 * 10) - time()) * 1000 : 0;
        $item['end_time']     = $end_time ?: 0;
        $data['imgs']         = $item['imgs'];
        $data['item']         = $item;
        $data['store']        = $store;
        unset($data['item']['store']);
        if(empty($data)){
            return json(['code'=>204,'msg'=>'没有内容']);
        }else{
            return json(['data'=>$data,'code'=>200,'msg'=>'成功']);
        }
    }

    /**
     * 单个商品下单用户列表
     */
    public function itemOrderUser(){
        $param['id']      = $this->request->param('id/d',0);
        $param['signkey'] = $this->request->param('signkey');
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $order = AllwinShopOrder::where(['shop_id' => $param['id']])->limit(6)->select();
        $data = [];
        if($order->isEmpty()){
            $user = SystemUser::where(['member_miniapp_id' => $this->miniapp_id])->field('face')->limit(6)->select()->toArray();
            $data = array_column($user,'face');
        }else{
            foreach ($order as $key => $value) {
                $data[$key] = $value->user->face;
            }
        }
        $new_order['id']          = 0;
        $new_order['create_time'] = 0;
        if($this->user){
            $info = AllwinShopOrder::where(['user_id'=> $this->user->id,'shop_id' =>$param['id'],'paid_at' => 0,'is_del' => 0])->field('id,create_time')->find();
            if($info){
                $create_time = (($info->create_time + 60 * 10) - time()) * 1000;
                if($create_time < 0){
                    $info->is_del = 1;
                    $info->save();
                }
                $new_order['id']          = $info->id;
                $new_order['create_time'] = $create_time;
            }
        }
        return enjson(200,'成功',['share' => $data,'order' => $new_order]);
    }
}